<?php

namespace App\Admin\Forms\Shop;

use App\Models\Shop\WxShop;
use App\Models\System\AdminUser;
use App\Models\System\RoleUser;
use App\Models\User\WxUser;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Models\Role;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class ShopExamineForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * 处理表单请求.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {

        $id = $input['id'];
        $status = $input['status'];
        $refuse_reason = $input['refuse_reason'];

        if(_empty_($id)){
            return $this->response()
                ->error('参数错误.');
        }

        if(_empty_($status) || !in_array($status, [1, 2])){
            return $this->response()
                ->error('参数错误.');
        }

        $shop = WxShop::find($id);
        if(_empty_($shop)){
            return $this->response()
                ->error('店铺不存在错误.');
        }

        if(!Role::where('slug', 'enterprise')->exists()){
            return $this->response()
                ->error('后台不存在商家（enterprise）角色，请先手动创建商家角色，并赋予基础的商家权限.');
        }

        DB::beginTransaction();
        try {
            // todo:
            if($status == 1){
                // 审核通过
                if(_empty_($shop->admin_user_id)){
                    $user = WxUser::find($shop->user_id);
                    // 初始化后台账号
                    $admin_user = new AdminUser();
                    $admin_user->username = $shop->user_id;
                    $admin_user->password = '$2y$10$kTcmXGFDYn.KW.z6TNu.EOb8P7TBWkRbGX1uhlCPzuwyr5GTa5LMe';
                    $admin_user->name = $user->user_name;
                    $admin_user->avatar = $user->user_avatar;
                    $admin_user->uid = $user->id;
                    $r = $admin_user->save();
                    if($r){
                        $role_id = Role::where('slug', 'enterprise')->value('id');
                        if(!_empty_($role_id)){
                            $role_user = new RoleUser();
                            $role_user->role_id = $role_id;
                            $role_user->user_id = $admin_user->id;
                            $r2 = $role_user->save();
                            if($r2){
//                                WxUser::where('id', $shop);
                                WxShop::where('id', $shop->id)->update(['admin_user_id'=>$admin_user->id, 'status' => 1]);
                                UserUtils::add_user_notice(6004, $shop->user_id, '店铺审核结果', '你的店铺申请已通过', 100, '', '');

                                DB::commit();
                                return $this->response()
                                    ->success('操作成功.')
                                    ->refresh();
                            }
                        }
                    }
                    DB::rollBack();
                    return $this->response()
                        ->error('错误.');
                }else{
                    WxShop::where('id', $shop->id)->update(['status' => 1]);
                    UserUtils::add_user_notice(6004, $shop->user_id, '店铺审核结果', '你的店铺申请已通过', 100, '', '');
                    DB::commit();
                    return $this->response()
                        ->success('操作成功.')
                        ->refresh();
                }
            }else if($status == 2){
                if(_empty_($refuse_reason)){
                    return $this->response()
                        ->error('请填写拒绝理由.');
                }
                WxShop::where('id', $shop->id)->update(['status' => 2, 'refuse_reason' => $refuse_reason]);
                // 发送通知
                UserUtils::add_user_notice(6004, $shop->user_id, '店铺审核结果', '你的店铺申请被管理员拒绝，拒绝理由：' . $refuse_reason, 100, '', '');

                DB::commit();
                return $this->response()
                    ->success('操作成功.')
                    ->refresh();
            }


        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->response()
                ->error('错误.');
        }

    }

    /**
     * 构建表单.
     */
    public function form()
    {
        $this->hidden('id')->value($this->payload["id"]);
        $this->radio('status', '审核结果')->options([1=>'通过', 2 => '拒绝'])->when(2, function (Form $form){
            $form->textarea('refuse_reason');
        })->default(1);
    }

}
